<?php
namespace app\index\controller;
use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use think\Validate;
use app\index\validate\Valid;

class Jxsgl extends Common
{

	//列表
    public function index()
    {
        $import = $this->request->param('import');
        $this->assign('import',$import);
        $title = $this->request->get('title');
        $sn = $this->request->get('sn');
        $zoning = $this->request->get('zoning');
        $zoninghead = $this->request->get('zoninghead');
        $provicehead = $this->request->get('provicehead');
        $provice = $this->request->get('provice');
        $channeltype = $this->request->get('channeltype');
        $city = $this->request->get('city');
        $cityhead = $this->request->get('cityhead');
        $stuff = $this->request->get('stuff');
        $this->assign(array('title'=>$title));
        $this->assign(array('sn'=>$sn));
        $this->assign(array('zoning'=>$zoning));
        $this->assign(array('zoninghead'=>$zoninghead));
        $this->assign(array('provice'=>$provice));
        $this->assign(array('provicehead'=>$provicehead));
        $this->assign(array('channeltype'=>$channeltype));
        $this->assign(array('city'=>$city));
        $this->assign(array('cityhead'=>$cityhead));
        $this->assign(array('stuff'=>$stuff));
        $where = [];
        $where['isdel'] = 0;
        if($title)
            $where['title'] = array('like','%'.$title.'%');
        if($import)
            $where['import'] = 1;
        if($sn)
            $where['sn'] = array('like','%'.$sn.'%');
        if($zoning)
            $where['zoning'] = array('exp','in(select id from cg_market_zoning where title like "%'.$zoning.'%")');
        if($zoninghead)
            $where['zoning'] = array('exp','in(select t.id from cg_market_zoning t join employee t2 on t.head = t2.id where t2.em_name like "%'.$zoninghead.'%")');
        if($provice)
            $where['provice'] = array('exp','in(select id from cg_market_provice where title like "%'.$provice.'%")');
        if($provicehead)
            $where['provice'] = array('exp','in(select t.id from cg_market_provice t join employee t2 on t.head = t2.id where t2.em_name like "%'.$provicehead.'%")');

        if($channeltype)
            $where['channeltype'] = array('exp','in(select id from cg_channel_types1 where title like "%'.$channeltype.'%")');

        if($city)
            $where['city'] = array('exp','in(select id from cg_market_city where title like "%'.$city.'%")');
        if($cityhead)
            $where['city'] = array('exp','in(select t.id from cg_market_city t join employee t2 on t.head = t2.id where t2.em_name like "%'.$cityhead.'%")');

        if($stuff){
            //根据模糊查询规则把admin对应的id全部查询出来
            $ids = Db::query("select id from employee where em_name like '%{$stuff}%'");
            $str = [];
            foreach($ids as $k=>$v){
                if($k==0)
                    $str[] = " like '%\"$v[id]\"%' ";
                else
                    $str[] = " stuff like '%\"$v[id]\"%' ";
            }
            $str = implode('or',$str);

            $where['stuff'] = array('exp',$str);
        }

        $count = Db::table('cg_jxs')->where($where)->count();
        $data = Db::table('cg_jxs')->order("id desc")->where($where)->paginate(10,$count);
//        echo Db::table('cg_jxs')->getLastSql();
        $page = $data->render();
        $data = $data->items();
         $maxpage=ceil($count/10);
        foreach($data as $k=>$v){
            $data[$k]['cusername'] = Db::table('users')->where(array('id'=>$v['cuser']))->value('login_name');
            $data[$k]['pusername'] = Db::table('users')->where(array('id'=>$v['puser']))->value('login_name');
            $data[$k]['provice'] = Db::table('cg_market_provice')->where(array('id'=>$v['provice']))->value('title');
            $data[$k]['zoning'] = Db::table('cg_market_zoning')->where(array('id'=>$v['zoning']))->value('title');
            $data[$k]['city'] = Db::table('cg_market_city')->where(array('id'=>$v['city']))->value('title');

            if($v['stuff']){
                $temp = unserialize($v['stuff']);
                $temp = implode(',',$temp);
                $temp = Db::query("select em_name from employee where id in(".$temp.")");
                $temp2 = [];
                foreach($temp as $v1){
                    $temp2[] = $v1['em_name'];
                }
                $data[$k]['stuff'] = $temp2;
            }

            $data[$k]['ctime'] = date('Y-m-d H:i',$v['ctime']);
            $data[$k]['ptime'] = date('Y-m-d H:i',$v['ptime']);
        }
        $this->assign('data',$data);
        $this->assign('page',$page);
		$this->assign('maxpage',$maxpage);
		$this->assign('count',$count);
        return $this->fetch('index');
    }
    public function add(){

//        print_r($_POST);
//        die;
        $validate = new Valid([
            'title|经销商名称'  => 'require|max:100|checkJxsmc|unique:cg_jxs',
            'zoning|销售分区'  => 'require',
            'provice|销售省份'  => 'require',
            'city|销售城市'  => 'require',
            'sn|经销商编号'  => 'require|unique:cg_jxs',
            'channeltype|渠道类型'  => 'require',
            'types|经销商等级'  => 'require',
            'cooptime|开始合作时间'  => 'require|dateFormat:Y-m-d',
            'addr|详细地址'  => 'require',
            'contact1|客户联系人1'  => 'require',
            'mobile1|手机1'  => 'require|cgMobile',
            'phone1|联系电话1'  => 'require|cgPhone',
            'mailaddr|联络邮寄地址'  => 'require',
            'cw_legalrepre|法定代表人'  => 'require',
            'cw_taxsn|税号'  => 'require',
            'cw_bank|开户行'  => 'require',
            'cw_banksn|开户账号'  => 'require',
            'cw_mailaddr|财务邮寄地址'  => 'require',
            'bs_contact|业务联系人'  => 'require',
            'bs_phone|业务联系固定电话'  => 'require|cgPhone',
            'bs_mobile|业务联系手机'  => 'require|cgMobile',
            'bs_fax|业务联系传真'  => 'require|cgPhone',
            'bs_rcv_unit|收货单位'  => 'require',
            'bs_rcv_addr|收货地址'  => 'require',
            'bs_rcv_one|收货人'  => 'require',
            'bs_rcv_phone|收货人电话'  => 'require|cgPhoneOrMobile',
            'lgs_rcv_addr|收货地址1'  => 'require',
            'lgs_rcv_one|收货人1'  => 'require',
            'lgs_rcv_phone|联系电话1'  => 'require|cgPhoneOrMobile',
            'costrate|经销商目标费用率'  => 'number',
        ]);
        $data = Request::instance()->post();
        if(isset($data['jxsll'])){
            $jxsll = $data['jxsll'];
            unset($data['jxsll']);
        }
        if (!$validate->check($data)) {
            echo  json_encode([
                "success"=>false,
                "msg"=>$validate->getError()
            ]);die;
        }



        if($data['stuff']){
            $data['stuff'] = explode(',',$data['stuff']);
            $data['stuff'] = serialize($data['stuff']);
        }

        $data['cuser'] = $_SESSION['think']['employee_id'];
        $data['cooptime'] = strtotime($data['cooptime']);
        $data['ctime'] = time();
        $data['puser'] = $_SESSION['think']['employee_id'];
        $data['ptime'] = time();
        if($data['attach']){
            $attachids = $data['attach'];
            $data['attach'] = serialize(explode(',',$data['attach']));
        }
        $bool = Db::table('cg_jxs')->insert($data);
        if(false !== $bool){
            $insetid = Db::table('cg_jxs')->getLastInsID();
            //更新附件表
            if(isset($attachids)){

                Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$insetid,'target_table'=>'cg_jxs'));
            }

            //增加附属联系信息表
            if(isset($jxsll)&&is_array($jxsll)){
                $temp  = [];

                foreach($jxsll['name'] as $k=>$v){
                    if($v=='')
                        continue;
                    $temp[] = [
                        'name'=>$v,
                        'jxs_id'=>$insetid,
                        'phone'=>$jxsll['phone1'][$k].'-'.$jxsll['phone2'][$k],
                        'mobile'=>$jxsll['mobile'][$k],
                        'fax'=>$jxsll['fax1'][$k].'-'.$jxsll['fax2'][$k],
                        'email'=>$jxsll['email'][$k],
                        'job'=>$jxsll['job'][$k],
                        'cuser'=>$_SESSION['think']['employee_id'],
                        'ctime'=>time(),
                        'puser'=>$_SESSION['think']['employee_id'],
                        'ptime'=>time(),
                    ];
                }
                Db::name('cg_jxs_ci')->insertAll($temp);
            }

            echo  json_encode([
                "success"=>true,
                "msg"=>"添加成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"添加失败"
            ]);die;
        }

    }

    //取消设置为直营经销商
    public function unsetDirect(){
        $data = [];
        $data['direct'] = 0;
        $id = $this->request->get('id');
        //记录日志-备份原记录
        $old = $this->log_start($id);
        $bool = Db::table('cg_jxs')->where(['id'=>$id])->update($data);
        if(false !== $bool){
            //记录日志-开始记录
            $this->log_end($id,$old);
            echo json_encode(array('flag'=>1,'msg'=>'设置成功！'));die;
        }else{
            echo json_encode(array('flag'=>0,'msg'=>'设置失败！'));die;
        }
    }
    //设置为直营经销商
    public function setDirect(){
        $data = [];
        $data['direct'] = 1;
        $id = $this->request->get('id');
        //记录日志-备份原记录
        $old = $this->log_start($id);
        $bool = Db::table('cg_jxs')->where(['id'=>$id])->update($data);
        if(false !== $bool){
            //记录日志-开始记录
            $this->log_end($id,$old);
            echo json_encode(array('flag'=>1,'msg'=>'设置成功！'));die;
        }else{
            echo json_encode(array('flag'=>0,'msg'=>'设置失败！'));die;
        }
    }

    //取消设置为直营经销商
    public function unsetImport(){
        $data = [];
        $data['import'] = 0;
        $id = $this->request->get('id');
        //记录日志-备份原记录
        $old = $this->log_start($id);
        $bool = Db::table('cg_jxs')->where(['id'=>$id])->update($data);
        if(false !== $bool){
            //记录日志-开始记录
            $this->log_end($id,$old);
            echo json_encode(array('flag'=>1,'msg'=>'设置成功！'));die;
        }else{
            echo json_encode(array('flag'=>0,'msg'=>'设置失败！'));die;
        }
    }
    //设置为直营经销商
    public function setImport(){
        $data = [];
        $data['import'] = 1;
        $id = $this->request->get('id');
        //记录日志-备份原记录
        $old = $this->log_start($id);
        $bool = Db::table('cg_jxs')->where(['id'=>$id])->update($data);
        if(false !== $bool){
            //记录日志-开始记录
            $this->log_end($id,$old);
            echo json_encode(array('flag'=>1,'msg'=>'设置成功！'));die;
        }else{
            echo json_encode(array('flag'=>0,'msg'=>'设置失败！'));die;
        }
    }

    //表单增加
    public function addAgency(){
        $import = $this->request->param('import');
        $this->assign('import',$import);

        $this->searchAllZoning();

        //查询渠道类型一
        $this->searchAllct1();

        return $this->fetch();
    }
    //查询分区并且赋值模板变量fenqu
    public function  searchAllZoning(){
        //查询分区
        $fenqu = Db::table('cg_market_zoning')->field('id,title')->select();
        $this->assign('fenqu',$fenqu);
    }
    //查询查询渠道类型一并且赋值模板变量cg_channel_types1
    public function  searchAllct1(){
        //查询分区
        $cg_channel_types1 = Db::table('cg_channel_types1')->field('id,title')->select();
        $this->assign('cg_channel_types1',$cg_channel_types1);
    }

    public function getcities(){
        $id = $this->request->get('id');
        $fenqu = Db::table('cg_market_city')->where(array('provice'=>$id))->select();
        echo '<option value="">请选择</option>';
        foreach($fenqu as $k=>$v) {
            echo '<option value="'.$v['id'].'">'.$v['title'].'</option>';
        }
    }

    //批量设置分区
    public function setprovice(){

        if($_POST){
            $cities = $this->request->post('cities');
            $provice = $this->request->post('provice');
            $cities = str_replace('-',',',$cities);
            $bool = Db::execute("update cg_market_city set provice='".$provice."' where id in(".$cities.")");
            if(false!==$bool){
                echo  json_encode([
                    "success"=>true,
                    "msg"=>"修改成功"
                ]);
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"修改失败"
                ]);
            }
            die;
        }

        $cities = $this->request->get('cities');
        $this->assign('cities',$cities);
        //查询分区
        $fenqu = Db::table('cg_market_zoning')->field('id,title')->select();
        $this->assign('fenqu',$fenqu);

        return $this->fetch();
    }
    public function updateview(){
        $id = $this->request->get('id');
        $data = Db::table('cg_market_city')->where(array('id'=>$id))->find();
        $data['em_name'] = Db::table('employee')->where(array('id'=>$data['head']))->value('em_name');

        $temp = unserialize($data['admin']);
        $temp = implode(',',$temp);
        $temp = Db::query("select em_name,id from employee where id in(".$temp.")");

        $data['admins'] = $temp;

        //查询所属分区id
        $data['zoning'] = Db::table('cg_market_provice')->where(array('id'=>$data['provice']))->value('zoning');
        $this->assign('data',$data);

        //查询分区
        $fenqu = Db::table('cg_market_zoning')->field('id,title')->select();
        $this->assign('fenqu',$fenqu);

        //查询改分区下的所有省份
        $shengfen = Db::table('cg_market_provice')->where('zoning',$data['zoning'])->select();
        $this->assign('shengfen',$shengfen);

        return $this->fetch();
    }

    //查询部门负责人
    public function selecthead(){
        return $this->fetch();
    }
    //查询部门负责人
    public function selectadmin(){
        return $this->fetch();
    }

    //查看对账单
    public function AgencyStatement(){
        return $this->fetch();
    }

    //查看详情
    public function AgencyDetail(){
        $id = $this->request->param('id');
        $data = Db::table('cg_jxs')->where(array('id'=>$id))->find();
        if($data){
            $data['zoning'] = Db::table('cg_market_zoning')->where('id',$data['zoning'])->value('title');
            $data['provice'] = Db::table('cg_market_provice')->where('id',$data['provice'])->value('title');
            $data['city'] = Db::table('cg_market_city')->where('id',$data['city'])->value('title');
            $data['channeltype'] = Db::table('cg_channel_types1')->where('id',$data['channeltype'])->value('title');
            $data['cooptime'] = date('Y-m-d',$data['cooptime']);
        }
        //查询旗下系统
        $data['systems'] = Db::table('cg_system t')
            ->join('cg_system_jxs t2','t2.system_id=t.id')
            ->where('t2.jxs_id',$id)
            ->field('t.id,t.title')
            ->select();
        $data['systems_num'] = Db::table('cg_system t')
            ->join('cg_system_jxs t2','t2.system_id=t.id')
            ->where('t2.jxs_id',$id)
            ->count();
        $this->assign('data',$data);
        return $this->fetch();
    }

    public function provicejson(){
        //查询所有省份
        $data = Db::table('employee')->field('em_name,id')->select();

        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }
    public function update(){

        $id = $this->request->post('id');
        $data = [];
        $data['id'] = $id;
        $data['title'] = $this->request->post('title');
        $data['head'] = $this->request->post('head');
        $data['admin'] = $this->request->post('admin');
        $data['provice'] = $this->request->post('provice');
        $validate = new Validate([
            'title|经销商名称'  => 'require|max:100|unique:cg_market_city',
            'id' => 'require|number',
            'head'  => 'require',
            'admin'  => 'require',
            'provice'  => 'require',
        ]);

        if (!$validate->check($data)) {
            echo  json_encode([
                "success"=>false,
                "msg"=>$validate->getError()
            ]);die;
        }

        $data['admin'] = explode(',',$data['admin']);
        $data['admin'] = serialize($data['admin']);
        $data['puser'] = $_SESSION['think']['employee_id'];
        $data['ptime'] = time();
        $bool = Db::table('cg_market_city')->where(array('id'=>$id))->update($data);
//        echo Db::table('cg_market_city')->getLastSql();
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"修改成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"修改失败"
            ]);die;
        }

    }

//    删除
    public function delete(){
        $id = $this->request->post('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $data = [];
        $data['isdel'] = 1;
        //记录日志-备份原记录
        $old = $this->log_start($id);
        $bool = Db::table('cg_jxs')->where(array('id'=>$id))->update($data);
        if(false !== $bool){
            //记录日志-开始记录
            $this->log_end($id,$old);
            echo  json_encode([
                "success"=>true,
                "msg"=>"删除成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"删除失败"
            ]);die;
        }
    }
//    批量删除经销商及其下属系统网点
    public function batchDel(){
        $id = $this->request->post('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $data = [];
        $data['isdel'] = 1;
        //记录日志-备份原记录
        $old = $this->log_start($id);
        $bool = Db::table('cg_jxs')->where(array('id'=>$id))->update($data);
        if(false !== $bool){

            //删除系统
            Db::table('cg_system')
                ->where(['id'=>['exp','in(select system_id from cg_system_jxs where jxs_id='.$id.')']])
                ->update($data);

            //删除网点
            Db::table('cg_net')
                ->where(array('system_id'=>['exp','in(select system_id from cg_system_jxs where jxs_id='.$id.')']))
                ->update($data);
            //记录日志-开始记录
            $this->log_end($id,$old);
            echo  json_encode([
                "success"=>true,
                "msg"=>"删除成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"删除失败"
            ]);die;
        }
    }
    public function qiyongContact(){
        $id = $this->request->post('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $data = [];
        $data['isdel'] = 0;

        $bool = Db::table('cg_jxs_ci')->where(array('id'=>$id))->update($data);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"删除成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"删除失败"
            ]);die;
        }
    }
    public function delContact(){
        $id = $this->request->post('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $data = [];
        $data['isdel'] = 1;
        $bool = Db::table('cg_jxs_ci')->where(array('id'=>$id))->update($data);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"删除成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"删除失败"
            ]);die;
        }
    }


    public function qiyong(){
        $id = $this->request->post('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $data = [];
        $data['isdel'] = 0;
        //记录日志-备份原记录
        $old = $this->log_start($id);
        $bool = Db::table('cg_jxs')->where(array('id'=>$id))->update($data);
        if(false !== $bool){
            //记录日志-开始记录
            $this->log_end($id,$old);
            echo  json_encode([
                "success"=>true,
                "msg"=>"启用成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"启用失败"
            ]);die;
        }
    }

//    回收站
    public function isdel(){
        $title = $this->request->get('title');
        $sn = $this->request->get('sn');
        $zoning = $this->request->get('zoning');
        $zoninghead = $this->request->get('zoninghead');
        $provicehead = $this->request->get('provicehead');
        $provice = $this->request->get('provice');
        $channeltype = $this->request->get('channeltype');
        $city = $this->request->get('city');
        $cityhead = $this->request->get('cityhead');
        $stuff = $this->request->get('stuff');
        $this->assign(array('title'=>$title));
        $this->assign(array('sn'=>$sn));
        $this->assign(array('zoning'=>$zoning));
        $this->assign(array('zoninghead'=>$zoninghead));
        $this->assign(array('provice'=>$provice));
        $this->assign(array('provicehead'=>$provicehead));
        $this->assign(array('channeltype'=>$channeltype));
        $this->assign(array('city'=>$city));
        $this->assign(array('cityhead'=>$cityhead));
        $this->assign(array('stuff'=>$stuff));
        $where = [];
        $where['isdel'] = 1;
        if($title)
            $where['title'] = array('like','%'.$title.'%');
        if($sn)
            $where['sn'] = array('like','%'.$sn.'%');
        if($zoning)
            $where['zoning'] = array('exp','in(select id from cg_market_zoning where title like "%'.$zoning.'%")');
        if($zoninghead)
            $where['zoning'] = array('exp','in(select t.id from cg_market_zoning t join employee t2 on t.head = t2.id where t2.em_name like "%'.$zoninghead.'%")');
        if($provice)
            $where['provice'] = array('exp','in(select id from cg_market_provice where title like "%'.$provice.'%")');
        if($provicehead)
            $where['provice'] = array('exp','in(select t.id from cg_market_provice t join employee t2 on t.head = t2.id where t2.em_name like "%'.$provicehead.'%")');

        if($channeltype)
            $where['channeltype'] = array('exp','in(select id from cg_channel_types1 where title like "%'.$channeltype.'%")');

        if($city)
            $where['city'] = array('exp','in(select id from cg_market_city where title like "%'.$city.'%")');
        if($cityhead)
            $where['city'] = array('exp','in(select t.id from cg_market_city t join employee t2 on t.head = t2.id where t2.em_name like "%'.$cityhead.'%")');

        if($stuff){
            //根据模糊查询规则把admin对应的id全部查询出来
            $ids = Db::query("select id from employee where em_name like '%{$stuff}%'");
            $str = [];
            foreach($ids as $k=>$v){
                if($k==0)
                    $str[] = " like '%\"$v[id]\"%' ";
                else
                    $str[] = " stuff like '%\"$v[id]\"%' ";
            }
            $str = implode('or',$str);

            $where['stuff'] = array('exp',$str);
        }

        $count = Db::table('cg_jxs')->where($where)->count();
        $data = Db::table('cg_jxs')->order("id desc")->where($where)->paginate(10,$count);
//        echo Db::table('cg_jxs')->getLastSql();
        $page = $data->render();
        $data = $data->items();
        $maxpage=ceil($count/10);
        foreach($data as $k=>$v){
            $data[$k]['cusername'] = Db::table('users')->where(array('id'=>$v['cuser']))->value('login_name');
            $data[$k]['pusername'] = Db::table('users')->where(array('id'=>$v['puser']))->value('login_name');
            $data[$k]['provice'] = Db::table('cg_market_provice')->where(array('id'=>$v['provice']))->value('title');
            $data[$k]['zoning'] = Db::table('cg_market_zoning')->where(array('id'=>$v['zoning']))->value('title');

            if($v['stuff']){
                $temp = unserialize($v['stuff']);
                $temp = implode(',',$temp);
                $temp = Db::query("select em_name from employee where id in(".$temp.")");
                $temp2 = [];
                foreach($temp as $v1){
                    $temp2[] = $v1['em_name'];
                }
                $data[$k]['stuff'] = $temp2;
            }

            $data[$k]['ctime'] = date('Y-m-d H:i',$v['ctime']);
            $data[$k]['ptime'] = date('Y-m-d H:i',$v['ptime']);
        }
        $this->assign('data',$data);
        $this->assign('page',$page);
		  $this->assign('maxpage',$maxpage);
		  $this->assign('count',$count);
        return $this->fetch();
    }
    //查询部门负责人
    public function selectsalesman(){
        return $this->fetch();
    }

    //上传附件
    public function fileupload(){

        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');

        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                // 成功上传后 获取上传信息
                // 输出 jpg
                $info->getExtension();
                // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                $info->getSaveName();
                // 输出 42a79759f284b767dfcb2a0197904287.jpg
                $info->getFilename();
                $data = [];
                $data['target_table'] =  'cg_jxs';
                $data['file_name'] =  $info->getFilename();
                $data['path'] =  dirname($info->getSaveName());
                $bool = Db::table('annex')->insert($data);
                $id = Db::table('annex')->getLastInsID();
                echo json_encode(array('id'=>$id));die;

            }else{
                // 上传失败获取错误信息
                echo $file->getError();
            }
        }
    }

    public function tab(){
        $key = $this->request->param('key');
        $id = $this->request->param('id');
        $this->assign('id',$id);

        switch($key){
            case 'delivery_address':
                return $this->fetch('jxsgl/tab/delivery_address');break;

            case 'fuzeMan':
                $data = Db::table('cg_jxs')->where('id',$id)->field('zoning,provice,city,stuff')->find();
                $data['zoning'] = Db::table('cg_market_zoning')->where('id',$data['zoning'])->value('title');
                $data['provice'] = Db::table('cg_market_provice')->where('id',$data['provice'])->value('title');
                $data['city'] = Db::table('cg_market_city')->where('id',$data['city'])->value('title');
                if($data['stuff']&&$data['stuff']!='0'){

                    $data['stuff'] = unserialize($data['stuff']);
                    $data['stuff'] = implode(',',$data['stuff']);

                    $data['stuff'] = Db::table('employee')->where("id in(".$data['stuff'].")")->field('id,em_name')->select();
                }
                $this->assign('data',$data);
                return $this->fetch('jxsgl/tab/fuzeMan');break;

            case 'yinglifenxi':
                return $this->fetch('jxsgl/tab/yinglifenxi');break;

            case 'marketChance':
                return $this->fetch('jxsgl/tab/marketChance');break;

            case 'contactRecord':
                return $this->fetch('jxsgl/tab/contactRecord');break;

            case 'commission_items':
                return $this->fetch('jxsgl/tab/commission_items');break;

            case 'quoteRecord':
                return $this->fetch('jxsgl/tab/quoteRecord');break;

            case 'costRecord':
                return $this->fetch('jxsgl/tab/costRecord');break;

            case 'compact':
                return $this->fetch('jxsgl/tab/compact');break;

            case 'despatch':
                return $this->fetch('jxsgl/tab/despatch');break;

            case 'bill':
                return $this->fetch('jxsgl/tab/bill');break;

            case 'inventory_records':
                return $this->fetch('jxsgl/tab/inventory_records');break;

            case 'sales_forecast':
                return $this->fetch('jxsgl/tab/sales_forecast');break;

            case 'document':
                $data = Db::table('cg_jxs')->where('id',$id)->field('attach')->value('attach');
                if($data){
                    $data = unserialize($data);
                    foreach($data as $k=>$v){
                        $temp = Db::table('annex')->where(array('id'=>$v))->find();

                        $temp['path'] = '/uploads/'.$temp['path'];

                        $data[$k] = $temp;
                    }
                }

                $this->assign('data',$data);
                return $this->fetch('jxsgl/tab/document');break;

            case 'image':
                return $this->fetch('jxsgl/tab/image');break;

            case 'evaluate':
                //查询系统评价信息
                $evaluation = Db::table('cg_jxs_evaluation')->where(['jxs_id'=>$id,'cuser'=>Session::get('employee_id')])->find();
                $data = [];
                $data['id'] = $id;
                $data['num'] = Db::table('cg_jxs_evaluation')->where('jxs_id',$id)->count();
                $data['evaluation'] = $evaluation;
                $this->assign('data',$data);
                return $this->fetch('jxsgl/tab/evaluate');break;

            case 'daily_record':
                $data = Db::table('cg_jxs_log')->order('ctime desc')->select();
                foreach($data as $k=>$v){
                    $data[$k]['cuser'] = Db::table('users')->where('id',$v['cuser'])->value('login_name');
                }
                $this->assign('data',$data);
                return $this->fetch('jxsgl/tab/daily_record');break;

            case 'order':
                return $this->fetch('jxsgl/tab/order');break;

            default:
                return $this->fetch('jxsgl/tab/contactMan');
        }

    }

    //修改经销商基本信息
    public function amendAgencyInfo(){
        $id = $this->request->param('id');

        if($_POST){

            $validate = new Valid([
                'title'  => 'require|max:100|checkJxsmc|unique:cg_jxs',
                'zoning'  => 'require',
                'provice'  => 'require',
                'city'  => 'require',
                'channeltype'  => 'require',
                'types'  => 'require',
                'cooptime'  => 'require|dateFormat:Y-m-d',
                'addr'  => 'require',
                'costrate'  => 'number',
            ]);
            $data = Request::instance()->post();
            $data['id'] = $id;
            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }


            if(isset($data['stuff'])){
                $data['stuff'] = explode(',',$data['stuff']);
                $data['stuff'] = serialize($data['stuff']);
            }

            $data['cooptime'] = strtotime($data['cooptime']);
            $data['puser'] = $_SESSION['think']['employee_id'];
            $data['ptime'] = time();

            //记录日志-备份原记录
            $old = $this->log_start($id);

            $bool = Db::table('cg_jxs')->where(array('id'=>$id))->update($data);
            if(false !== $bool){

                //记录日志-开始记录
                $this->log_end($id,$old);

                echo  json_encode([
                    "success"=>true,
                    "msg"=>"修改成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"修改失败"
                ]);die;
            }

            die;
        }

        $data = Db::table('cg_jxs')->where('id',$id)->find();
        $this->assign('data',$data);

        //查询所有销售分区
        $this->searchAllZoning();

        //查询指定分区下的所有省份
        $provice = Db::table('cg_market_provice')->where(array('zoning'=>$data['zoning']))->select();
        $this->assign('provice',$provice);

        //查询指定省份下的所有城市
        $city = Db::table('cg_market_city')->where(array('provice'=>$data['provice']))->select();
        $this->assign('city',$city);

        //查询渠道类型一
        $this->searchAllct1();

        return $this->fetch('jxsgl/tab/amendAgencyInfo');
    }

    //修改经销商联系信息
    public function amendContactInfo(){
        $id = $this->request->param('id');

        if($_POST){

            $validate = new Valid([
                'contact1'  => 'require',
                'mobile1'  => 'require|cgMobile',
                'phone1'  => 'require|cgPhone',
                'mailaddr'  => 'require',
                'cw_legalrepre'  => 'require',
                'cw_taxsn'  => 'require',
                'cw_bank'  => 'require',
                'cw_banksn'  => 'require',
                'cw_mailaddr'  => 'require',
                'bs_contact'  => 'require',
                'bs_phone'  => 'require|cgPhone',
                'bs_mobile'  => 'require|cgMobile',
                'bs_fax'  => 'require|cgPhone',
                'bs_rcv_unit'  => 'require',
                'bs_rcv_addr'  => 'require',
                'bs_rcv_one'  => 'require',
                'bs_rcv_phone'  => 'require|cgPhoneOrMobile',
                'lgs_rcv_addr'  => 'require',
                'lgs_rcv_one'  => 'require',
                'lgs_rcv_phone'  => 'require|cgPhoneOrMobile'
            ]);
            $data = Request::instance()->post();
            $data['id'] = $id;
            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }


            if(isset($data['stuff'])){
                $data['stuff'] = explode(',',$data['stuff']);
                $data['stuff'] = serialize($data['stuff']);
            }


            $data['puser'] = $_SESSION['think']['employee_id'];
            $data['ptime'] = time();

            //记录日志-备份原记录
            $old = $this->log_start($id);

            $bool = Db::table('cg_jxs')->where(array('id'=>$id))->update($data);
            if(false !== $bool){

                //记录日志-开始记录
                $this->log_end($id,$old);
                echo  json_encode([
                    "success"=>true,
                    "msg"=>"修改成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"修改失败"
                ]);die;
            }

            die;
        }

        $data = Db::table('cg_jxs')->where('id',$id)->find();

        //查询经销商联系人信息附属表的信息
        $data['ci'] = Db::table('cg_jxs_ci')->where(array('jxs_id'=>$data['id']))->select();

        $this->assign('data',$data);

        return $this->fetch('jxsgl/tab/amendContactInfo');
    }


    //修改业务人员
    public function updateStuff(){
        $id = $this->request->param('id');

        if($_POST){
            $data = Request::instance()->post();

            if($data['stuff']){
                $data['stuff'] = explode(',',$data['stuff']);
                $data['stuff'] = serialize($data['stuff']);
            }
//            print_r($data);die;
            //记录日志-备份原记录
            $old = $this->log_start($id);
            $bool  = Db::table('cg_jxs')->where('id',$id)->update($data);

            //记录日志-开始记录
            $this->log_end($id,$old);

            if(false === $bool){
                echo  json_encode([
                    "success"=>false,
                    "msg"=>'修改失败'
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>true,
                    "msg"=>'成功'
                ]);die;
            }
        }

        $data = Db::table('cg_jxs')->where('id',$id)->field('zoning,provice,city,stuff')->find();
        $data['zoning'] = Db::table('cg_market_zoning')->where('id',$data['zoning'])->value('title');
        $data['provice'] = Db::table('cg_market_provice')->where('id',$data['provice'])->value('title');
        $data['city'] = Db::table('cg_market_city')->where('id',$data['city'])->value('title');
        if($data['stuff']&&$data['stuff']!='0'){

            $data['stuff'] = unserialize($data['stuff']);
            $data['stuff'] = implode(',',$data['stuff']);

            $data['stuff'] = Db::table('employee')->where("id in(".$data['stuff'].")")->field('id,em_name')->select();
        }


        $this->assign('data',$data);
        return $this->fetch('jxsgl/tab/updateStuff');
    }

    public function addsaleChance(){
        return $this->fetch('jxsgl/tab/addsaleChance');
    }

    /**
     * 修改附件
     * @return mixed
     */
    public function updateAttach(){
        $attach = $this->request->post('attach');
        $id = $this->request->param('id');
        $attach = trim($attach,',');
        $attachids = $attach;

        //先把旧的附件查出来
        $aids = Db::table('cg_jxs')->where('id',$id)->value('attach');
        $old = $aids;
        if($aids){
            $aids = unserialize($aids);
        }
        if(!is_array($aids)){
            $aids = [];
        }

        //删除附件
        $remove = $this->request->post('remove');
        if($remove){

            $aids = array_diff($aids,explode(',',$remove));
            Db::table('annex')->where('id','in',$remove)->update(['isdel'=>1]);
//                echo Db::table('annex')->getLastSql();
        }

        //新增附件
        if($attach) {
            $attachids = $attach;
            //新旧合并
            $attach = serialize(array_merge(explode(',', $attach), $aids));
        }else { //非新增
            $attach = serialize($aids);
        }

        $data = [];
        $data['attach'] = $attach;
        //记录日志-备份原记录
        $old = $this->log_start($id);
        Db::table('cg_jxs')->where(array('id'=>$id))->update($data);
        //记录日志-开始记录
        $this->log_end($id,$old);
        //新增附件\更新附件表
        if(isset($attachids)){

            Db::table('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$id,'target_table'=>'cg_jxs'));
        }

        echo json_encode(['success'=>true,'msg'=>'修改成功']);
    }


    /**
     * 提交评价
     */
    public function subEvaluation(){
        $data = [];
        $data['p1'] = $this->request->post('p1');
        $data['p2'] = $this->request->post('p2');
        $data['p3'] = $this->request->post('p3');
        $data['p4'] = $this->request->post('p4');
        $data['p5'] = $this->request->post('p5');
        $data['p6'] = $this->request->post('p6');
        $data['p7'] = $this->request->post('p7');
        $data['p8'] = $this->request->post('p8');
        $data['p9'] = $this->request->post('p9');
        $data['p10'] = $this->request->post('p10');
        $data['p11'] = $this->request->post('p11');
        $data['p12'] = $this->request->post('p12');
        $data['p13'] = $this->request->post('p13');
        $data['jxs_id'] = $this->request->post('jxs_id');
        $data['cuser'] = Session::get('employee_id');
        $data['ctime'] = time();

        $evaluation = Db::table('cg_jxs_evaluation')->where(['jxs_id'=>$data['jxs_id'],'cuser'=>Session::get('employee_id')])->count();
        if($evaluation>0){
            echo  json_encode([
                "success"=>false,
                "msg"=>"不能重复评价"
            ]);die;
        }
        $bool = Db::table('cg_jxs_evaluation')->insert($data);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"评价成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"评价失败"
            ]);die;
        }
    }

    //经销商操作日志
    public function log_start($id){
        $data = Db::table('cg_jxs')->where('id',$id)->find();
        return $data;
    }
    //经销商操作日志
    public function log_end($id,$old){
        $new = Db::table('cg_jxs')->where('id',$id)->find();
        $msg = [];
        if($new&&$old){
            if($old['title'] != $new['title']){
                $msg[] = '经销商名称由‘'.$old['title'].'’变成‘'.$new['title'].'’';
            }
            if($old['brief'] != $new['brief']){
                $msg[] = '描述信息由‘'.$old['brief'].'’变成‘'.$new['brief'].'’';
            }
            if($old['zoning'] != $new['zoning']){
                $msg[] = '所属大区由‘'.Db::table('cg_market_zoning')->where('id',$old['zoning'])->value('title').'’变成‘'.Db::table('cg_market_zoning')->where('id',$new['zoning'])->value('title').'’';
            }
            if($old['provice'] != $new['provice']){
                $msg[] = '所属省份由‘'.Db::table('cg_market_provice')->where('id',$old['provice'])->value('title').'’变成‘'.Db::table('cg_market_provice')->where('id',$new['provice'])->value('title').'’';
            }
            if($old['city'] != $new['city']){
                $msg[] = '所属城市由‘'.Db::table('cg_market_city')->where('id',$old['city'])->value('title').'’变成‘'.Db::table('cg_market_city')->where('id',$new['city'])->value('title').'’';
            }
            if($old['sn'] != $new['sn']){
                $msg[] = '经销商编号由‘'.$old['sn'].'’变成‘'.$new['sn'].'’';
            }
            if($old['channeltype'] != $new['channeltype']){
                $msg[] = '所属渠道类型由‘'.Db::table('cg_channel_types1')->where('id',$old['channeltype'])->value('title').'’变成‘'.Db::table('cg_channel_types1')->where('id',$new['channeltype'])->value('title').'’';
            }
            if($old['direct'] != $new['direct']){
                if($old['direct'] ==1)
                    $msg[] = '设置为直营客户';
                else
                    $msg[] = '取消设置为直营客户';
            }
            if($old['import'] != $new['import']){
                if($old['import'] ==1)
                    $msg[] = '设置为重点客户';
                else
                    $msg[] = '取消设置为重点客户';
            }
            if($old['types'] != $new['types']){
                $msg[] = '所属经销商等级由‘'.Db::table('cg_jxs_types')->where('id',$old['types'])->value('title').'’变成‘'.Db::table('cg_jxs_types')->where('id',$new['types'])->value('title').'’';
            }
            if($old['cooptime'] != $new['cooptime']){
                $msg[] = '开始合作时间由‘'.date('Y-m-d',$old['cooptime']).'’变成‘'.date('Y-m-d',$new['cooptime']).'’';
            }
            if($old['costrate'] != $new['costrate']){
                $msg[] = '经销商目标费用率由‘'.$old['costrate'].'%’变成‘'.$new['costrate'].'%’';
            }
            if($old['invoicetype'] != $new['invoicetype']){
                if($old['invoicetype'] ==1)
                    $msg[] = '发票类型由普通发票变成增值税发票';
                else
                    $msg[] = '发票类型由增值税发票变成普通发票';
            }
            if($old['stuff'] != $new['stuff']){
                if($old['stuff']&&$new['stuff']){
                    $old['stuff'] = unserialize($old['stuff']);
                    $new['stuff'] = unserialize($new['stuff']);
                    $add = array_diff($new['stuff'],$old['stuff']);
                    $del = array_diff($old['stuff'],$new['stuff']);
                    if($add){
                        $add = implode(',',$add);
                        $daibiao = Db::table('employee')->where("id in($add)")->field('em_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['em_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '添加了业务代表'.$daibiao2;
                    }
                    if($del){
                        $del = implode(',',$del);
                        $daibiao = Db::table('employee')->where("id in($del)")->field('em_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['em_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '删除了业务代表'.$daibiao2;
                    }
                }elseif($old['stuff']){
                    $old['stuff'] = unserialize($old['stuff']);

                    if($old['stuff']){
                        $del = implode(',',$old['stuff']);
                        $daibiao = Db::table('employee')->where("id in(".$old['stuff'].")")->field('em_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['em_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '删除了业务代表'.$daibiao2;
                    }
                }else{
                    $new['stuff'] = unserialize($new['stuff']);
                    $add = $new['stuff'];
                    if($add){
                        $add = implode(',',$add);
                        $daibiao = Db::table('employee')->where("id in($add)")->field('em_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['em_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '添加了业务代表'.$daibiao2;
                    }
                }
            }
            if($old['addr'] != $new['addr']){
                $msg[] = '详细地址由‘'.$old['addr'].'’变成‘'.$new['addr'].'’';
            }
            if($old['contact1'] != $new['contact1']){
                $msg[] = '客户联系人1由‘'.$old['contact1'].'’变成‘'.$new['contact1'].'’';
            }
            if($old['mobile1'] != $new['mobile1']){
                $msg[] = '客户联系人1的手机由‘'.$old['mobile1'].'’变成‘'.$new['mobile1'].'’';
            }
            if($old['phone1'] != $new['phone1']){
                $msg[] = '客户联系人1的联系电话由‘'.$old['phone1'].'’变成‘'.$new['phone1'].'’';
            }
            if($old['contact2'] != $new['contact2']){
                $msg[] = '客户联系人2由‘'.$old['contact2'].'’变成‘'.$new['contact2'].'’';
            }
            if($old['mobile2'] != $new['mobile2']){
                $msg[] = '客户联系人2的手机由‘'.$old['mobile2'].'’变成‘'.$new['mobile2'].'’';
            }
            if($old['phone2'] != $new['phone2']){
                $msg[] = '客户联系人2的联系电话由‘'.$old['phone2'].'’变成‘'.$new['phone2'].'’';
            }
            if($old['mailaddr'] != $new['mailaddr']){
                $msg[] = '客户联系人2的邮寄地址由‘'.$old['mailaddr'].'’变成‘'.$new['mailaddr'].'’';
            }
            if($old['zipcode'] != $new['zipcode']){
                $msg[] = '经销商联络信息的邮编由‘'.$old['zipcode'].'’变成‘'.$new['zipcode'].'’';
            }
            if($old['cw_legalrepre'] != $new['cw_legalrepre']){
                $msg[] = '财务法定代表人由‘'.$old['cw_legalrepre'].'’变成‘'.$new['cw_legalrepre'].'’';
            }
            if($old['cw_lrphone'] != $new['cw_lrphone']){
                $msg[] = '财务法人固定电话由‘'.$old['cw_lrphone'].'’变成‘'.$new['cw_lrphone'].'’';
            }
            if($old['cw_lrmobile'] != $new['cw_lrmobile']){
                $msg[] = '财务法人手机由‘'.$old['cw_lrmobile'].'’变成‘'.$new['cw_lrmobile'].'’';
            }
            if($old['cw_qualification'] != $new['cw_qualification']){
                $msg[] = '纳税资格由‘'.$old['cw_qualification'].'’变成‘'.$new['cw_qualification'].'’';
            }
            if($old['cw_lremail'] != $new['cw_lremail']){
                $msg[] = '财务法人电子邮箱由‘'.$old['cw_lremail'].'’变成‘'.$new['cw_lremail'].'’';
            }
            if($old['cw_taxsn'] != $new['cw_taxsn']){
                $msg[] = '财务税号由‘'.$old['cw_taxsn'].'’变成‘'.$new['cw_taxsn'].'’';
            }
            if($old['cw_bank'] != $new['cw_bank']){
                $msg[] = '财务开户行由‘'.$old['cw_bank'].'’变成‘'.$new['cw_bank'].'’';
            }
            if($old['cw_banksn'] != $new['cw_banksn']){
                $msg[] = '财务开户账号由‘'.$old['cw_banksn'].'’变成‘'.$new['cw_banksn'].'’';
            }
            if($old['cw_creditperiod'] != $new['cw_creditperiod']){
                $msg[] = '财务信用账期由‘'.$old['cw_creditperiod'].'天’变成‘'.$new['cw_creditperiod'].'天’';
            }
            if($old['cw_creditlimit'] != $new['cw_creditlimit']){
                $msg[] = '财务信用额由‘'.$old['cw_creditlimit'].'元’变成‘'.$new['cw_creditlimit'].'元’';
            }
            if($old['cw_mailaddr'] != $new['cw_mailaddr']){
                $msg[] = '财务邮寄地址由‘'.$old['cw_mailaddr'].'’变成‘'.$new['cw_mailaddr'].'’';
            }
            if($old['cw_zipcode'] != $new['cw_zipcode']){
                $msg[] = '财务邮编由‘'.$old['cw_zipcode'].'’变成‘'.$new['cw_zipcode'].'’';
            }
            if($old['cw_contact'] != $new['cw_contact']){
                $msg[] = '财务联系人由‘'.$old['cw_contact'].'’变成‘'.$new['cw_contact'].'’';
            }
            if($old['cw_phone'] != $new['cw_phone']){
                $msg[] = '财务联系电话由‘'.$old['cw_phone'].'’变成‘'.$new['cw_phone'].'’';
            }
            if($old['cw_email'] != $new['cw_email']){
                $msg[] = '财务电子邮箱由‘'.$old['cw_email'].'’变成‘'.$new['cw_email'].'’';
            }
            if($old['bs_contact'] != $new['bs_contact']){
                $msg[] = '业务联系人由‘'.$old['bs_contact'].'’变成‘'.$new['bs_contact'].'’';
            }
            if($old['bs_phone'] != $new['bs_phone']){
                $msg[] = '业务联系固定电话由‘'.$old['bs_phone'].'’变成‘'.$new['bs_phone'].'’';
            }
            if($old['bs_mobile'] != $new['bs_mobile']){
                $msg[] = '业务联系手机由‘'.$old['bs_mobile'].'’变成‘'.$new['bs_mobile'].'’';
            }
            if($old['bs_fax'] != $new['bs_fax']){
                $msg[] = '业务联系传真由‘'.$old['bs_fax'].'’变成‘'.$new['bs_fax'].'’';
            }
            if($old['bs_rcv_unit'] != $new['bs_rcv_unit']){
                $msg[] = '业务收货单位由‘'.$old['bs_rcv_unit'].'’变成‘'.$new['bs_rcv_unit'].'’';
            }
            if($old['bs_rcv_addr'] != $new['bs_rcv_addr']){
                $msg[] = '业务收货地址由‘'.$old['bs_rcv_addr'].'’变成‘'.$new['bs_rcv_addr'].'’';
            }
            if($old['bs_rcv_one'] != $new['bs_rcv_one']){
                $msg[] = '业务收货人由‘'.$old['bs_rcv_one'].'’变成‘'.$new['bs_rcv_one'].'’';
            }
            if($old['bs_rcv_phone'] != $new['bs_rcv_phone']){
                $msg[] = '业务收货人电话由‘'.$old['bs_rcv_phone'].'’变成‘'.$new['bs_rcv_phone'].'’';
            }
            if($old['isdel'] != $new['isdel']){
                if($old['isdel'] ==1)
                    $msg[] = '从回收站重新启用了该经销商';
                else
                    $msg[] = '把该经销商挪到了回收站';
            }
            if($old['attach'] != $new['attach']){
                if($old['attach']&&$new['attach']){
                    $old['attach'] = unserialize($old['attach']);
                    $new['attach'] = unserialize($new['attach']);
                    $add = array_diff($new['attach'],$old['attach']);
                    $del = array_diff($old['attach'],$new['attach']);
                    if($add){
                        $add = implode(',',$add);
                        $daibiao = Db::table('annex')->where("id in($add)")->field('file_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['file_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '添加了附件'.$daibiao2;
                    }
                    if($del){
                        $del = implode(',',$del);
                        $daibiao = Db::table('annex')->where("id in($del)")->field('file_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['file_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '删除了附件'.$daibiao2;
                    }
                }elseif($old['attach']){
                    $old['attach'] = unserialize($old['attach']);

                    if($old['attach']){
                        $del = implode(',',$old['attach']);
                        $daibiao = Db::table('annex')->where("id in(".$old['attach'].")")->field('file_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['file_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '删除了附件'.$daibiao2;
                    }
                }else{
                    $new['attach'] = unserialize($new['attach']);
                    $add = $new['attach'];
                    if($add){
                        $add = implode(',',$add);
                        $daibiao = Db::table('annex')->where("id in($add)")->field('file_name')->select();
                        $daibiao2 = [];
                        foreach($daibiao as $k=>$v){
                            $daibiao2[] = '‘'.$v['file_name'].'’';
                        }
                        $daibiao2 = implode(',',$daibiao2);
                        $msg[] = '添加了附件'.$daibiao2;
                    }
                }
            }
            if($msg){
                $msg = '修改了编号为\''.$old['sn'].'\'的经销商‘'.$old['title'].'’,'.implode(',',$msg);
                //插入日志
                Db::table('cg_jxs_log')->insert(['content'=>$msg,
                    'jxs_id'=>$new['id'],
                    'cuser'=>Session::get("employee_id"),
                    'ctime'=>time()
                ]);
            }

        }
    }

    public function map(){
        $id = $this->request->param('id');
        if($_POST){
            $data = [];
            $data['lng'] = $this->request->post('lng');
            $data['lat'] = $this->request->post('lat');
            $data['addr'] = $this->request->post('detailAddress');

            $bool = Db::table('cg_jxs')->where('id',$id)->update($data);
            if(false !== $bool){
                echo json_encode(['success'=>true,'msg'=>'ok']);die;
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);die;
            }
        }
        return $this->fetch();
    }

    //在地图上显示
    public function mapShow(){
        $id = $this->request->param('import');
        $where = [];
        if($id){
            $where['import'] = 1;
        }
        $data = db('cg_jxs')->where($where)->field('lat,lng,addr detailAddress,title,id')->select();
        $this->assign('data',$data);
        return $this->fetch();
    }


public function lianluoagency(){
        return  $this->fetch();
    }
public function lianluoagencyisdel(){
        return  $this->fetch();
    }
}
